/**
 * 使用express、http-proxy-middleware构建的一个本地反向代理服务器
 * 将http://localhost:4000代理到https://api.github.com
 * 
 * 1、启动：nodemon ./src/server/proxy-server.js
 * 2、访问地址：http://localhost:4000
 */

const express = require('express');
const { createProxyMiddleware } = require('http-proxy-middleware');
const app = express();

// 允许所有域名跨域访问
app.all('*', (req, res, next) => {
  res.header("Access-Control-Allow-Origin", "*");
  res.header("Access-Control-Allow-Headers", "Content-Type,Content-Length, Authorization, Accept,X-Requested-With");
  res.header("Access-Control-Allow-Methods", "PUT,POST,GET,DELETE,OPTIONS");
  res.header("X-Powered-By", 'express/4.17.3');

  // 跨域请求CORS中的预请求
  if (req.method == "OPTIONS") {
    // 让options请求快速返回
    res.send(200)
  } else {
    next()
  }
})

// 获取所有链接地址: https://api.github.com
// 获取所有用户信息: https://api.github.com/users
// 获取表情包: https://api.github.com/emojis
const proxy = (path = '/') => {
  return createProxyMiddleware({
    target: `https://api.github.com${path}`,
    changeOrigin: true,
  })
}

app.use(proxy('/'));
app.use(proxy('/users'));
app.use(proxy('/emojis'));

// 启动服务器，监听端口4000
app.listen(4000, () => {
  console.log("server is running at http://localhost:4000")
})